var http = require('../../../utils/https');
Page({
  data: {
    tabs: ["全部", "待付款", "待发货", "待收货", "待评价"],
    currentTab: 0,
    userId: wx.getStorageSync('userInfo').userId,
    // 获取点击的订单id
    orderId:null,
    // 全部状态的订单
    allStatusOrders: [],
    // 订单状态字典：数字 -> 文字描述
    statusMap: {
      0: '待付款',
      1: '待发货',
      2: '待收货',
      3: '待评价',
      4: '已完成',
      5: '已取消',
      6: '拼团中',
    },

    isLoading: false,
    // 支付弹窗状态
    showPayPopup: false,
    paying: false,
    userBalance: '0.00',
    totalAmount: '0.00',
    currentPayOrderId: null,
    // 状态订单
    pendingPayment: [],
    pendingDelivery: [],
    pendingPickup: [],
    pendingReview: [],
    otherStatus: [],

    isLoading: false,
    pageNum: 1, // 当前页码（从1开始）
    pageSize: 10, // 每页条数
    total: 0, // 总条数（用于判断是否有更多数据）
    loading: false, // 是否正在加载
    noMore: false // 是否没有更多数据
  },

  // 返回my页面
  navigateBack() {
    wx.switchTab({
      url: '/pages/my/my',
    })
  },

  onLoad() {
    // 合并所有订单到 allOrders，实际可从接口获取后处理
    // const allOrders = [
    //     ...this.data.pendingPaymentOrders,
    //     ...this.data.pendingDeliveryOrders,
    //     ...this.data.pendingReceiptOrders,
    //     ...this.data.pendingEvaluationOrders,
    //     ...this.data.completedOrders
    // ];
    this.getCoupon();
    this.getAllOrders(this.data.pageSize, this.data.pageNum);
    // this.setData({ allOrders });
    this.setData({
      isLoading: false
    });
  },

  // onHide（）
  // onHide(){
  //   this.getAllOrders(10, 1)
  // },
  // onshow()
  onShow() {
    this.getAllOrders(10, 1)
  },

  // 获取当前优惠券类型
  // GET 请求
  getCoupon() {
    http.GET('/coupon/coupons/list', null, (res) => {
      console.log('获取当前优惠券成功:', res);
    }, (err) => {
      console.error('获取当前优惠券失败:', err);
    });
  },
  // 上拉触底事件
  onReachBottom() {
    // 触发加载下一页
    if (!this.data.loading && !this.data.noMore) {
      this.getAllOrders(this.data.pageSize, this.data.pageNum);
    }
  },

  // 获取全部订单列表（支持分页加载）
  getAllOrders(pageSize, pageNum,status) {
    // 防止重复请求
    if (this.data.loading || this.data.noMore) return;

    // 显示加载状态
    this.setData({
      loading: true
    });

    // 发起请求
    http.GET('/order/orders/list', {
      userId: this.data.userId,
      pageSize: pageSize,
      pageNum: pageNum
      // status:status
    }, (res) => {
      console.log('获取全部订单成功:', res);

      // 假设接口返回格式：{ rows: 列表数据, total: 总条数 }
      const {
        rows,
        total
      } = res;

      // 格式化价格为两位小数
      const formattedList = rows.map(item => ({
        ...item,
        totalAmount: Number(item.totalAmount).toFixed(2)
      }));

      // 合并数据（第一页直接赋值，后续页追加）
      const newOrders = pageNum === 1 ?
        formattedList :
        [...this.data.allStatusOrders, ...formattedList];

      // 判断是否还有更多数据
      const noMore = newOrders.length >= total;

      // 更新页面数据
      this.setData({
        allStatusOrders: newOrders,
        total: total,
        pageNum: pageNum + 1, // 页码+1，下次加载下一页
        loading: false,
        noMore: noMore
      });

    }, (err) => {
      console.error('获取全部订单失败:', err);
      // 错误时也需要关闭加载状态
      this.setData({
        loading: false
      });
    });
  },


  // 封装分析订单状态的方法
  // 在获取订单列表后进行拆分
  splitOrdersByStatus() {
    const {
      allStatusOrders
    } = this.data;
    // 初始化各状态数组
    const pendingPayment = []; // 待付款 (status=0)
    const pendingDelivery = []; // 待发货 (status=2)
    const pendingPickup = []; // 待自取 (status=6)
    const pendingReview = []; // 待评价 (status=7)
    const otherStatus = []; // 其他状态（可选）
    // 遍历订单数组进行分类
    allStatusOrders.forEach(order => {
      switch (order.status) {
        case 0:
          pendingPayment.push(order);
          break;
        case 2:
          pendingDelivery.push(order);
          break;
        case 6:
          pendingPickup.push(order);
          break;
        case 7:
          pendingReview.push(order);
          break;
        default:
          // 处理其他未定义的状态（如已完成、已取消等）
          otherStatus.push(order);
          break;
      }
    });
    // 更新到数据中，供页面渲染使用
    this.setData({
      pendingPayment,
      pendingDelivery,
      pendingPickup,
      pendingReview,
      otherStatus
    });
    console.log('订单分类结果：', {
      待付款: pendingPayment,
      待发货: pendingDelivery,
      待自取: pendingPickup,
      待评价: pendingReview,
      其他状态: otherStatus
    });
  },



  switchTab(e) {
    const index = e.currentTarget.dataset.index;
    this.setData({
      currentTab: index
    });
  },

  getStatusClass(status) {
    switch (status) {
      case '待付款':
        return 'pending-payment';
      case '待发货':
        return 'pending-delivery';
      case '待收货':
        return 'pending-receipt';
      case '待评价':
        return 'pending-evaluation';
      case '交易完成':
        return 'completed';
      default:
        return '';
    }
  },
  // 封装取消订单的请求
  cancelOrderRequest(orderId) {
    // GET 请求
    http.DELETE(`/order/orders/${orderId}`, null, (res) => {
      console.log('发出取消订单成功:', res);
    }, (err) => {
      console.error('发出取消订单失败:', err);
    });
  },
  // 取消订单
  cancelOrder(e) {
    const orderId = e.currentTarget.dataset.orderid;
    const isSelfPick = e.currentTarget.dataset.isselfpick;

    // 根据是否为自提订单决定跳转页面
    const targetPage = isSelfPick ? '/my/pages/xtxCancelSelf/xtxCancelSelf' : '/my/pages/xtxCancel/xtxCancel';
    wx.showModal({
      title: '确认取消',
      content: '确定要取消这个订单吗？',
      success: (res) => {
        if (res.confirm) {
          wx.navigateTo({
            url: targetPage + '?orderId=' + orderId,
            success: () => {
              this.cancelOrderRequest(orderId)
              console.log('跳转到取消订单详情页面成功，订单ID:', orderId, '自提:', isSelfPick);
            },
            fail: (err) => {
              console.error('跳转到取消订单详情页面失败:', err);
              wx.showToast({
                title: '页面跳转失败',
                icon: 'none'
              });
            }
          });
        }
      }
    })

  },

  // 获取本地 userId
  getUserIdFromStorage() {
    try {
      let userInfo = wx.getStorageSync('userInfo');
      if (typeof userInfo === 'string') {
        userInfo = JSON.parse(userInfo || '{}');
      }
      return (userInfo && userInfo.userId) || wx.getStorageSync('userInfo').userId || null;
    } catch (e) {
      return wx.getStorageSync('userInfo').userId || null;
    }
  },
  // 获取余额
  fetchUserBalance(userId) {
    if (!userId) return;
    http.GET('/balance/list', {
      userId
    }, (res) => {
      console.log('获取余额成功', res);
      if (res.code == 200) {
        const balance = res.rows[0].balance;
        this.setData({
          userBalance: Number(balance || 0).toFixed(2)
        });
      }
    }, (err) => {
      console.warn('获取余额失败', err);
    });
  },
  // 查询订单应付金额
  fetchOrderPayable(totalAmount) {
    if (!totalAmount) return;
    this.setData({
      totalAmount: Number(totalAmount || 0).toFixed(2)
    });
  },

  // 列表页“立即付款”
  payOrder(e) {
    const totalAmount = e.currentTarget.dataset.totalamount;
    const orderId = e.currentTarget.dataset.orderid;
    const userId = this.getUserIdFromStorage();
    console.log('e', e);
    console.log('totalAmount', totalAmount);
    this.setData({
      orderId:orderId
    })
    console.log('orderId', this.data.orderId);
    
    console.log('userId', userId);
    this.setData({
      currentPayOrderId: orderId
    });
    this.fetchOrderPayable(totalAmount);
    this.fetchUserBalance(userId);
    this.setData({
      showPayPopup: true
    });
  },

  // 关闭弹窗
  closePayPopup() {
    this.setData({
      showPayPopup: false,
      paying: false
    });
  },

  // 列表页确认支付
  confirmBalancePay(e) {
    if (this.data.paying) return;

    const userBalance = parseFloat(this.data.userBalance || 0);
    const totalAmount = parseFloat(this.data.totalAmount || 0);

    if (userBalance < totalAmount) {
      wx.showModal({
        title: '余额不足',
        content: '余额不足，是否前往充值？',
        success: (res) => {
          if (res.confirm) {
            wx.navigateTo({
              url: '/my/pages/recharge/recharge'
            });
          }
        },
      });
      return;
    }

    this.setData({
      paying: true
    });

    // 支付接口
    setTimeout(() => {
      this.setData({
        paying: false,
        showPayPopup: false
      });
      // 1. 准备URL参数（userId和balance）
      const urlParams = `?userId=${this.data.userId}&balance=${this.data.totalAmount}`;
      // 2. 准备请求体参数（对应BalanceVo的字段）
      // 注意：需要根据后端BalanceVo类的实际字段调整
      const requestBody = {
        orderId: this.data.orderId,
      };
      console.log('orderId', this.data.orderId);
      // 3. 发送请求（URL拼接参数 + 请求体传参）
      http.PUT(`/balance/decrease${urlParams}`, requestBody,
        (res) => {
          if(res.code ==200){
            console.log('支付成功:', res);
            wx.showToast({
              title: '支付成功',
              icon: 'success',
              duration: 1500
            });
            wx.navigateTo({
              url: '/shopCart/pages/paysuccess/paysuccess?orderId=' + this.data.currentPayOrderId
            });
          }else{
            wx.showToast({
              title: '支付失败',
              icon: 'success',
              duration: 1500
            });
          }
        },
        (err) => {
          console.error('支付失败:', err);
          wx.showToast({
            title: '支付失败',
            icon: 'success',
            duration: 1500
          });
        }
      );
    }, 800);
  },

  applyRefund(e) {
    const orderId = e.currentTarget.dataset.orderid;
    // 修改跳转路径为xtxRefund页面，并携带订单ID参数
    wx.navigateTo({
      url: '/my/pages/xtxRefund/xtxRefund?orderId=' + orderId,
      success: () => {
        console.log('跳转到退款页面成功，订单ID:', orderId);
      },
      fail: (err) => {
        console.error('跳转到退款页面失败:', err);
        wx.showToast({
          title: '页面跳转失败',
          icon: 'none'
        });
      }
    });
  },

  // 跳转到退款页面
  goToRefund(e) {
    const orderId = e.currentTarget.dataset.orderid;
    wx.navigateTo({
      url: '/my/pages/xtxRefund/xtxRefund?orderId=' + orderId,
      success: () => {
        console.log('跳转到退款页面成功，订单ID:', orderId);
      },
      fail: (err) => {
        console.error('跳转到退款页面失败:', err);
        wx.showToast({
          title: '页面跳转失败',
          icon: 'none'
        });
      }
    });
  },
  // 待收货
  goToNoAccept(e) {
    const orderId = e.currentTarget.dataset.orderid;
    wx.navigateTo({
      url: '/my/pages/xtxNoAccept/xtxNoAccept?orderId=' + orderId,
      success: () => {
        console.log('跳转到待收货页面成功，订单ID:', orderId);
      },
      fail: (err) => {
        console.error('跳转到待收货页面失败:', err);
        wx.showToast({
          title: '页面跳转失败',
          icon: 'none'
        });
      }
    });
  },
  checkLogistics(e) {
    const orderId = e.currentTarget.dataset.orderid;
    wx.showToast({
      title: '查看物流接口待完善',
      icon: 'none'
    });
  },

  // 确认订单成功
  confirmReceipt(e) {
    const orderId = e.currentTarget.dataset.orderid;
    http.PUT('/order/orders', { id:orderId }, (res) => {
      console.log('确认订单成功:', res);
      if(res.code == 200){
        // 显示确认收货成功提示
        wx.showToast({
          title: '确认收货成功',
          icon: 'success',
          duration: 1500
        });

        // 延迟跳转到待评价页面
        setTimeout(() => {
          wx.navigateTo({
            url: '/my/pages/xtxOrdersReview/xtxOrdersReview?orderId=' + orderId,
            success: () => {
              console.log('跳转到待评价页面成功，订单ID:', orderId);
            },
            fail: (err) => {
              console.error('跳转到待评价页面失败:', err);
              wx.showToast({
                title: '页面跳转失败',
                icon: 'none'
              });
            }
          });
        }, 1500);
      }
    }, (err) => {
      console.error('确认订单失败:', err);
    });
   
  },

  goEvaluate(e) {
    const orderId = e.currentTarget.dataset.orderid;
    wx.navigateTo({
      url: '/my/pages/xtxOrdersReview/xtxOrdersReview?orderId=' + orderId,
      success: () => {
        console.log('跳转到评价页面成功，订单ID:', orderId);
      },
      fail: (err) => {
        console.error('跳转到评价页面失败:', err);
        wx.showToast({
          title: '页面跳转失败',
          icon: 'none'
        });
      }
    });
  },

  repeatOrder(e) {
    const orderId = e.currentTarget.dataset.orderid;
    wx.showToast({
      title: '再来一单接口待完善',
      icon: 'none'
    });
  },

  // 跳转到订单详情页面
  goToOrderDetail(e) {
    const orderId = e.currentTarget.dataset.orderid;
    const status = e.currentTarget.dataset.status;
    const isSelfPick = e.currentTarget.dataset.isselfpick;
    const index = e.currentTarget.dataset.index;
    console.log('orderId', orderId);
    console.log('status', status);
    console.log('isSelfPick', isSelfPick);
    console.log('index', index);
    // 根据订单状态决定跳转页面
    if (this.data.statusMap[status] === '待付款') {
      const targetPage = isSelfPick ? '/my/pages/xtxSelfNoPay/xtxSelfNoPay' : '/my/pages/xtxNoPay/xtxNoPay';
      // 存储对象（键名自定义，如 "currentOrderData"）
      // wx.setStorageSync('currentOrderData', this.data.allStatusOrders[index]);
      wx.navigateTo({
        url: targetPage + '?orderId=' + orderId,
        success: () => {
          console.log('跳转到订单详情页面成功，订单ID:', orderId, '自提:', isSelfPick);
        },
        fail: (err) => {
          console.error('跳转到订单详情页面失败:', err);
          wx.showToast({
            title: '页面跳转失败',
            icon: 'none'
          });
        }
      });
    } else if (this.data.statusMap[status] === '待自取') {
      // 存储对象（键名自定义，如 "currentOrderData"）
      wx.setStorageSync('currentOrderData', this.data.allStatusOrders[index]);
      // 跳转到待收货详情页面
      wx.navigateTo({
        url: '/my/pages/xtxNoAccept/xtxNoAccept?orderId=' + orderId,
        success: () => {
          console.log('跳转到待收货详情页面成功，订单ID:', orderId);
        },
        fail: (err) => {
          console.error('跳转到待收货详情页面失败:', err);
          wx.showToast({
            title: '页面跳转失败',
            icon: 'none'
          });
        }
      });
    } else if (this.data.statusMap[status] === '待评价') {
      // 存储对象（键名自定义，如 "currentOrderData"）
      wx.setStorageSync('currentOrderData', this.data.allStatusOrders[index]);
      // 跳转到待评价详情页面
      wx.navigateTo({
        url: '/my/pages/xtxNoReview/xtxNoReview?orderId=' + orderId,
        success: () => {
          console.log('跳转到待评价详情页面成功，订单ID:', orderId);
        },
        fail: (err) => {
          console.error('跳转到待评价详情页面失败:', err);
          wx.showToast({
            title: '页面跳转失败',
            icon: 'none'
          });
        }
      });
    } else if (this.data.statusMap[status] === '已完成') {
      // 存储对象（键名自定义，如 "currentOrderData"）
      wx.setStorageSync('currentOrderData', this.data.allStatusOrders[index]);
      // 跳转到已完成详情页面
      wx.navigateTo({
        url: '/my/pages/xtxFinished/xtxFinished?orderId=' + orderId,
        success: () => {
          console.log('跳转到已完成详情页面成功，订单ID:', orderId);
        },
        fail: (err) => {
          console.error('跳转到已完成详情页面失败:', err);
          wx.showToast({
            title: '页面跳转失败',
            icon: 'none'
          });
        }
      });
    }
  }
});